<?php


namespace models\Business;


use models\Exception\Business\IntegralproductException;
use models\Exception\Business\UserException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\IntegralproductService;
use Yaf\Registry;

class Exchange
{
    static public function getExchange($id = 0) {
        try {
            if (! isset($id) || empty($id))
                throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_ID_IS_EMPTY, IntegralproductException::INTEGRALPRODUCT_ID_IS_EMPTY_NO);

            return IntegralproductService::getInstance()->getOne($id);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     * @param array $parameters
     * @return array|mixed|null
     * @throws IntegralproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function editExchange($parameters = []) {
        try {$update_arr = [];
            if (! isset($parameters['id']) || empty($parameters['id']))
                throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_ID_IS_EMPTY, IntegralproductException::INTEGRALPRODUCT_ID_IS_EMPTY_NO);

            if (isset($parameters['name']))
                $update_arr['name'] = $parameters['name'];
            if (isset($parameters['price']))
                $update_arr['price'] = $parameters['price'];
            if (isset($parameters['exchange']))
                $update_arr['exchange'] = $parameters['exchange'];
            if (isset($parameters['icon'])) {
                $icon = strpos($parameters['icon'], Registry::get('config')['application']['host']) !== false ?
                    str_replace(Registry::get('config')['application']['host'], '', $parameters['icon']) : $parameters['icon'];
                $update_arr['icon'] = $icon;
            }
            if (isset($parameters['type']))
                $update_arr['type'] = $parameters['type'];
            if (isset($parameters['stats']))
                $update_arr['stats'] = $parameters['stats'];
            if (isset($parameters['sales']))
                $update_arr['sales'] = $parameters['sales'];
            if (isset($parameters['fake_sales']))
                $update_arr['fake_sales'] = $parameters['fake_sales'];
            if (isset($parameters['unit']))
                $update_arr['unit'] = $parameters['unit'];

            if (!empty($update_arr)) {
                if (!isset($parameters['from_api']) || $parameters['from_api'] == false) {
                    $update_arr['updated_by'] = Registry::get('jwt_info')->id;
                    $update_arr['updated_at'] = date("Y-m-d H:i:s", time());
                }

                $exchange = IntegralproductService::getInstance()->update($update_arr, $parameters['id']);

            } else
                $exchange = IntegralproductService::getInstance()->getOne($parameters['id']);

            return $exchange;
        } catch (IntegralproductException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            if ($e->getCode() == '130001')
                throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_EDIT_FAILURE, IntegralproductException::INTEGRALPRODUCT_EDIT_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            if ($e->getCode() == '110002')
                throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_EDIT_FAILURE, IntegralproductException::INTEGRALPRODUCT_EDIT_FAILURE_NO);
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     * @param array $parameters
     * @return array
     * @throws IntegralproductException
     */
    static public function createExchange($parameters = []) {
        try {
            $icon = strpos($parameters['icon'], Registry::get('config')['application']['host']) !== false ?
                str_replace(Registry::get('config')['application']['host'], '', $parameters['icon']) : $parameters['icon'];
            // $name = "", $icon = "", $type = 0, $price = 0.00, $exchange = 0.00,
            // $stats = 0, $created_by = 0, $created_at = "", $updated_by = 0, $updated_at = ""
            return IntegralproductService::getInstance()->create($parameters['name'], $icon, $parameters['type'], $parameters['price'],
                $parameters['exchange'], isset($parameters['stats']) ? $parameters['stats'] : 0,
                0, isset($parameters['fake_sales']) ? $parameters['fake_sales'] : 0,
                isset($parameters['unit']) ? $parameters['unit'] : '份',
                Registry::get('jwt_info')->id,
                date('Y-m-d H:i:s'), Registry::get('jwt_info')->id, date('Y-m-d H:i:s', time()));
        } catch (ModelDriverException $e) {
            throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE, IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE_NO);
        } catch (ModelException $e) {
            throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE, IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE_NO);
        } catch (ModelReflectionException $e) {
            throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE, IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE_NO);
        } catch (ModelSqlException $e) {
            throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE, IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE_NO);
        } catch (TransformerException $e) {
            throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE, IntegralproductException::INTEGRALPRODUCT_CREATE_FAILURE_NO);
        }
    }

    /**
     * @param array $parameters
     * @return array|mixed
     * @throws IntegralproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     * @throws UserException
     */
    static public function getExchangeList($parameters = []) {
        try {
            $rules = $condition = [];
            if (isset($parameters['type']))
                array_push($rules, ['field' => 'type', 'op' => 'eq', 'data' => $parameters['type']]);
            if (isset($parameters['stats']))
                array_push($rules, ['field' => 'stats', 'op' => 'eq', 'data' => $parameters['stats']]);
            if (isset($parameters['name']))
                array_push($rules, ['field' => 'name', 'op' => 'nc', 'data' => '%' . $parameters['name'] . '%']);

            if (!empty($rules))
                $condition = ['groupOp' => 'AND', 'rules' => $rules];
//            exit(json_encode($condition));

            $exchange = IntegralproductService::getInstance()->getList(
                isset($parameters['page']) ? $parameters['page'] : 1,
                isset($parameters['page_size']) ? $parameters['page_size'] : 10,
                isset($parameters['sort']) ? $parameters['sort'] : 'desc',
                isset($parameters['order']) ? $parameters['order'] : 'id',
                $condition
            );
            $exchange = User::getUsersByModule($exchange);

            foreach ($exchange['data'] as $idx => $val) {
                if (strpos($val['icon'], 'http://') === false && strpos($val['icon'], 'https://') === false)
                    $exchange['data'][$idx]['icon'] = Registry::get('config')['application']['host'] . $val['icon'];
                $exchange['data'][$idx]['type'] = (int)$val['type'];
                $exchange['data'][$idx]['stats'] = (int)$val['stats'];
                if (isset($parameters['from_api']) || $parameters['from_api'] === true) {
                    $exchange['data'][$idx]['sales'] += $val['fake_sales'];
                    unset($exchange['data'][$idx]['fake_sales']);
                }
                $exchange['data'][$idx]['price'] = sprintf('%.0f', $val['price']);
            }

            return $exchange;
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            if ($e->getCode() == '110002')
                throw new UserException(UserException::USER_IS_NOT_EXISTS, UserException::USER_IS_NOT_EXISTS_NO);
            throw $e;
            throw new IntegralproductException(IntegralproductException::INTEGRALPRODUCT_IS_NOT_EXISTS, IntegralproductException::INTEGRALPRODUCT_IS_NOT_EXISTS_NO);
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }


    }

}
